#include "registerdialog.h"
#include <QAction>
#include <QCryptographicHash>
#include <QJsonDocument>
#include <QLineEdit>
#include <QRegularExpression>
#include "httpmanager.h"
#include "ui_registerdialog.h"

RegisterDialog::RegisterDialog(QWidget *parent, unsigned int countDown)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog)
    , _countDown(countDown)
{
    ui->setupUi(this);
    ui->stackedWidget->setCurrentWidget(ui->page);
    ui->reg_edt_password->setEchoMode(QLineEdit::Password);
    ui->reg_edt_confirm->setEchoMode(QLineEdit::Password);
    ui->reg_err_tip->clear();
    ui->reg_err_tip->setProperty("state", "normal");
    repolish(ui->reg_err_tip);
    // 为密码和确认密码编辑框增加输入是否可见的action
    QAction *passwd_action = new QAction(ui->reg_edt_password);
    QAction *confirm_action = new QAction(ui->reg_edt_password);
    passwd_action->setIcon(QIcon(":/icon/icon/unvisible.png"));
    confirm_action->setIcon(QIcon(":/icon/icon/unvisible.png"));
    ui->reg_edt_password->addAction(passwd_action, QLineEdit::TrailingPosition);
    ui->reg_edt_confirm->addAction(confirm_action, QLineEdit::TrailingPosition);

    connect(passwd_action, &QAction::triggered, this, [this, passwd_action](bool checked) {
        if (ui->reg_edt_password->echoMode() == QLineEdit::Password) {
            ui->reg_edt_password->setEchoMode(QLineEdit::Normal);
            passwd_action->setIcon(QIcon(":/icon/icon/visible.png"));
        } else {
            ui->reg_edt_password->setEchoMode(QLineEdit::Password);
            passwd_action->setIcon(QIcon(":/icon/icon/unvisible.png"));
        }
    });

    connect(confirm_action, &QAction::triggered, this, [this, confirm_action](bool checked) {
        if (ui->reg_edt_confirm->echoMode() == QLineEdit::Password) {
            ui->reg_edt_confirm->setEchoMode(QLineEdit::Normal);
            confirm_action->setIcon(QIcon(":/icon/icon/visible.png"));
        } else {
            ui->reg_edt_confirm->setEchoMode(QLineEdit::Password);
            confirm_action->setIcon(QIcon(":/icon/icon/unvisible.png"));
        }
    });

    // 注册
    connect(HttpManager::GetInstance().get(),
            &HttpManager::sig_reg_mod_finish,
            this,
            &RegisterDialog::slot_reg_mod_finish);
    //注册请求回调函数
    initHttpHandlers();
    connect(ui->reg_edt_username, &QLineEdit::editingFinished, this, &RegisterDialog::CheckUserValid);
    connect(ui->reg_edt_email, &QLineEdit::editingFinished, this, &RegisterDialog::CheckEmailValid);
    connect(ui->reg_edt_password,
            &QLineEdit::editingFinished,
            this,
            &RegisterDialog::CheckPassWordValid);

    connect(ui->reg_edt_confirm, &QLineEdit::editingFinished, this, &RegisterDialog::CheckPassWordValid);

    connect(ui->reg_edt_verify, &QLineEdit::editingFinished, this, &RegisterDialog::CheckVerifyValid);
    // 创建定时器
    _timer = new QTimer(this);
    // 连接槽和信号
    connect(_timer, &QTimer::timeout, this, [this] {
        if (_countDown == 0) {
            _timer->stop();
            emit sigSwitchLogin();
            return;
        }
        _countDown--;
        QString str = QString("注册成功，%1s后登录").arg(_countDown);
        ui->tip_label->setText(str);
    });
}

RegisterDialog::~RegisterDialog()
{
    qDebug() << "RegisterDialog 析构\n";
    delete ui;
}

void RegisterDialog::on_reg_btn_cancel_clicked()
{
    emit sigSwitchLogin();
}
// 获取验证码
void RegisterDialog::on_reg_btn_req_clicked()
{
    //验证邮箱格式
    if (!CheckEmailValid()) {
        return;
    }
    QJsonObject json_obj;
    json_obj["email"] = ui->reg_edt_email->text();
    HttpManager::GetInstance()->PostHttpReq(QUrl(gate_url_prefix + "/get_verifycode"),
                                            json_obj,
                                            ReqId::ID_GET_VARIFY_CODE,
                                            Modules::REGISTERMOD);
}

void RegisterDialog::slot_reg_mod_finish(ReqId id, QString res, ErrorCode ec)
{
    if (ec != ErrorCode::SUCCESS) {
        showTip("网路请求错误！");
        return;
    }
    // 解析Json字符串
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if (jsonDoc.isNull()) {
        showTip("Json 解析失败");
        return;
    }
    // json 解析错误
    if (!jsonDoc.isObject()) {
        showTip("json解析失败");
        return;
    }
    // 调用回调函数
    _handlers[id](jsonDoc.object());
}

void RegisterDialog::showTip(const QString &err_str, bool success)
{
    ui->reg_err_tip->setText(err_str);
    if (success) {
        ui->reg_err_tip->setProperty("state", "normal");
    } else {
        ui->reg_err_tip->setProperty("state", "error");
    }
    repolish(ui->reg_err_tip);
}

void RegisterDialog::initHttpHandlers()
{
    // 注册获取验证码回包的逻辑
    _handlers.insert(ReqId::ID_GET_VARIFY_CODE, [this](const QJsonObject &jsonObject) {
        int error = jsonObject["error"].toInt();
        if (error != ErrorCode::SUCCESS) {
            showTip("参数错误");
            return;
        }
        auto email = jsonObject["email"].toString();
        showTip("验证码已经发送到邮箱，注意查收！", true);
        qDebug() << "email is " << email << "\n";
    });
    // 注册用户回包逻辑
    _handlers.insert(ReqId::ID_REG_USER, [this](const QJsonObject &jsonObject) {
        int error = jsonObject["error"].toInt();
        if (error != ErrorCode::SUCCESS) {
            showTip("参数错误", false);
            return;
        }
        auto email = jsonObject["email"].toString();
        showTip("用户注册成功", true);
        qDebug() << "emial is " << email;
        ChageTipPage();
    });
}

bool RegisterDialog::CheckUserValid()
{
    if (ui->reg_edt_username->text().isEmpty()) {
        AddTipErr(TipErr::TIP_USER_ERR, tr("用户名不能为空"));
        return false;
    }
    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool RegisterDialog::CheckEmailValid()
{
    //验证邮箱格式
    QString email = ui->reg_edt_email->text();
    QRegularExpression regex(R"(^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$)");
    bool match = regex.match(email).hasMatch();
    if (!match) {
        AddTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱地址不正确"));
        return false;
    }
    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool RegisterDialog::CheckPassWordValid()
{
    QString pass = ui->reg_edt_password->text();
    QString confirm = ui->reg_edt_confirm->text();
    if (pass.length() < 6 || pass.length() > 15) {
        AddTipErr(TipErr::TIP_PWD_ERR, tr("密码长度应为6-15"));
        return false;
    }
    // 创建一个正则表达式
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if (!match) {
        AddTipErr(TipErr::TIP_PWD_ERR, tr("不能包含非法字符串"));
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_ERR);
    if (pass != confirm) {
        AddTipErr(TipErr::TIP_PWD_CONFIRM, tr("密码和确认密码不匹配"));
        return false;
    }
    DelTipErr(TipErr::TIP_PWD_CONFIRM);
    return true;
}

bool RegisterDialog::CheckVerifyValid()
{
    QString verify = ui->reg_edt_verify->text();
    if (verify.isEmpty()) {
        AddTipErr(TipErr::TIP_VERIFY_ERR, tr("验证码不能为空"));
        return false;
    } else if (verify.length() != 4) {
        AddTipErr(TipErr::TIP_VERIFY_ERR, tr("验证码长度必须为4"));
        return false;
    } else {
        DelTipErr(TipErr::TIP_VERIFY_ERR);
        return true;
    }
}

void RegisterDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips);
}

void RegisterDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if (_tip_errs.isEmpty()) {
        ui->reg_err_tip->clear();
        return;
    } else {
        showTip(_tip_errs.begin().value());
    }
}

void RegisterDialog::ChageTipPage()
{
    _timer->stop();
    ui->stackedWidget->setCurrentWidget(ui->page_2);
    _timer->start(1000);
}

void RegisterDialog::on_reg_btn_ok_clicked()
{
    if (ui->reg_edt_username->text().isEmpty()) {
        showTip("用户名不能为空", false);
        return;
    }
    if (ui->reg_edt_email->text().isEmpty()) {
        showTip("邮箱不能为空", false);
        return;
    }
    if (ui->reg_edt_password->text().isEmpty()) {
        showTip("密码不能为空", false);
        return;
    }
    if (ui->reg_edt_confirm->text().isEmpty()) {
        showTip("确认密码不能为空", false);
        return;
    }
    if (ui->reg_edt_verify->text().isEmpty()) {
        showTip("验证码不能为空", false);
        return;
    }
    if (ui->reg_edt_password->text() != ui->reg_edt_confirm->text()) {
        showTip("两次输入密码不同", false);
        return;
    }
    // 对用户密码进行加密
    QString encrypted_pwd = QCryptographicHash::hash(ui->reg_edt_password->text().toUtf8(),
                                                     QCryptographicHash::Sha1)
                                .toHex();
    // 发送http请求注册用户
    QJsonObject json_obj;
    json_obj["user"] = ui->reg_edt_username->text();
    json_obj["email"] = ui->reg_edt_email->text();
    json_obj["passwd"] = encrypted_pwd;
    json_obj["verifycode"] = ui->reg_edt_verify->text();
    HttpManager::GetInstance()->PostHttpReq(QUrl(gate_url_prefix + "/user_register"),
                                            json_obj,
                                            ReqId::ID_REG_USER,
                                            Modules::REGISTERMOD);
}
// 返回登录按钮
void RegisterDialog::on_reg_btn_back_clicked()
{
    _timer->stop();
    emit sigSwitchLogin();
    return;
}
